import Paging from '../../../wxjs/Paging.js'
import getLocation from '../../../wxjs/getLocation.js'
// import screen from '../../../wxjs/screen.js'
import navToNext from '../../../wxjs/navToNext.js'
const app = getApp();

var pag = new Paging();

var data = {
  isLogin: false,
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  showModalStatus:false,
  isShadowOver: false,
  curId:1,
  navs: [{
    id: 1,
    text: '挑战赛',
  }, {
    id: 0,
    text: '团课',
  }, 
  ],
  tabId:4,
  cityIndex:0,
  areaIndex: 0,
  areaList: null,
  storeList: null,
  
};

var currentPage = {
  data,
  login,
  tapPage,
  classListParam: {},
  classUrl: app.serAddrs.getLectureList,
  challengeListParam:{},
  challengeUrl: app.serAddrs.getMatchList,
  reqUrl: app.serAddrs.getLectureList,
  getClassList,//获取团课列表
  changeTime,//切换时间
  changeTag,
  changeCity,
  changeAreas,
  changeStore,
  clearStore,
  changeOver,
  traverse,
  submitScreen,
  resetScreen,

  getChallengeList,

  getSearchLabelByType,//获取筛选标签
  typeParams: {}, //获取筛选标签参数
  timeLable:{},
  getMore,
  signUp, //支付接口
  payment,

  onLoad,
  checkDrop, //下拉选择
  selectDay, //日期选择
  completeLocation, //定位获取完成（成功，失败）
  openLocation, //查看位置
  callBack, //列表请求成功
  cutNavs,
  showModal,
  hideModal,
  toPayPage,
  onShow,
  onShareAppMessage: function() {}
};

var page = Object.assign({}, pag.func(), getLocation, app.navToNext, screen, currentPage);

Page(page)

function onShow() {
  var that = this
  const userInfo = wx.getStorageSync('user')
  if (userInfo) {
    this.setData({
      isLogin: true
    })
  }
  // that.tapPage()
  // app.xlogin.reLogin(function (res) {
  //   setTimeout(() => {
  that.cutNavs(1)
  //   }, 100)
  // });
}
function login(){
  const that = this;
  app.xlogin.getUser(function (res) {
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    }

    myInfo = app.isNavigateToBind();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    } else {
      that.setData({
        isLogin: true
      })
    }
  })
}

function tapPage(){
  const userInfo =wx.getStorageSync('user')
  if (!userInfo) {
    this.login()
  } else {
    this.setData({
      isLogin: true
    })
  }
}

function onLoad(options) {
  const that = this;
  this.tapPage()

  // let userId;
  // 团课、挑战赛切换tabid
  let navId = options && options.navId || 1;
  let uuid = options && options.uuid || "";
  // 邀请者uuid
  let invitorUuid = options && options.invitorUuid || "";
  // 邀请活动id
  let activityUuid = options && options.activityUuid || "";
  // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
  var scene = options && options.q && decodeURIComponent(options.q) || '';
  // console.log("【league】options======>", options);
  // console.log("【league】scene======>", scene);
  // 普通二维码进入怎么也得有10个字符
  if (scene.length > 10) {
    // 是否为json格式校验
    var tempScenes = scene.split("params=");
    if (tempScenes.length > 1) {
      tempScenes = tempScenes[1];
      var firstChar = tempScenes.charAt(0);
      var lastChar = tempScenes.charAt(tempScenes.length - 1);
      if (firstChar == "{" && lastChar == "}") {
        tempScenes = JSON.parse(tempScenes);
        // userId = tempScenes.userId;
        uuid = tempScenes.uuid;
        invitorUuid = tempScenes.invitorUuid;
        activityUuid = tempScenes.activityUuid;
        navId = tempScenes.navId || 0;
      }
    }
  }

  that.setData({
    curId:navId
  })

  if (invitorUuid) {
    app.invite.invitorUuid = invitorUuid;
    app.invite.activityUuid = activityUuid;
    // 异步获取用户信息
    app.xlogin.reLogin();
  }

  if (uuid) {
    wx.navigateTo({
      url: `${app.xhx_route.leagueDetails}?uuid=${uuid}`,
    })
  }
  that.getSearchLabelByType(4);

  app.xlogin.reLogin(function (res) {
    setTimeout(() => {
      that.cutNavs(1)
    }, 300)
  });
}
function toPayPage(e){
  const that = this;
  var challengeId = e.target.dataset.id || 0;
  let totalPrice = e.target.dataset.price || 0;
  if (totalPrice == 0 || !challengeId) return false;
  // 判断用户登录
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;
  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  let curItem = null;
  this.data.matchList.forEach(item => {
    if (item.id == challengeId) {
      curItem = item
    }
  })
  if (!curItem) return false;
  wx.navigateTo({
    url: '/pages/pay/pay?MatchType=1&item=' + JSON.stringify(curItem)
  })
}
function signUp(e){
  const that = this;
  var challengeId=e.target.dataset.id||0;
  let totalPrice = e.target.dataset.price || 0;
  if (totalPrice == 0 || !challengeId) return false;
  // 判断用户登录
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;
  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  var payParam={};
  payParam.tV2MatchScheduleId = challengeId;
  payParam.wxMold = 1;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.challengeByWXPay,
    data: payParam,
    cancelToast: true,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    success: function (ores) {
      that.payment(ores.data, challengeId);
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })
}
function payment(data, challengeId) {
  const that = this;

  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      // wx.navigateTo({
      //   url: that.data.xhx_route.challenge + '?uuid=' + challengeId,
      // })
      that.cutNavs(1);
    },
    fail(res) {
      app.middleware.showToast( "支付失败");
    },
    complete: function (res) {
      
    }
  })
}

function selectDay(event) {
  const that = this;
  const isLocation = that.data.isLocation;
  const time = event.detail.time;
  that.classListParam.dateTime = time || '';
  that.challengeListParam.startTime = time || '';

  if(that.data.curId==0){
    if (isLocation) {
      // 初始化
      that.getClassList();
    } else {
      that.getLocation();
    }
  }else if(that.data.curId==1){
    that.getChallengeList();
  }
}

function completeLocation(res) {
  const that = this;
  let latitude = res.latitude || '';
  let longitude = res.longitude || '';

  that.setData({
    latitude,
    longitude
  })
  that.typeParams.latitude = that.data.latitude;
  that.typeParams.longitude = that.data.longitude;
  that.getClassList();
}
function cutNavs(e) {
  const that=this;
  var id = typeof e === 'object' ? e.target.dataset.id : e
  that.setData({
    curId: id
  })
  if(id==0){
    that.getClassList();
  }else if(id==1){
    that.getChallengeList();
  }
}
function getClassList(){
  const that=this;
  // 初始化intervalTimes
  that.reqUrl = that.classUrl;
  if (!that.classListParam.latitude) that.classListParam.latitude = that.data.latitude;
  if (!that.classListParam.longitude) that.classListParam.longitude = that.data.longitude;
  if (!that.classListParam.areas) that.classListParam.areas = [];
  if (!that.classListParam.gymTypeIds) that.classListParam.gymTypeIds = [];
  if (!that.classListParam.intervalTimes) that.classListParam.intervalTimes = [];
  if (!that.classListParam.tGoodsLabelNameUuids) that.classListParam.tGoodsLabelNameUuids = [];
  if (!that.classListParam.tGymUuids) that.classListParam.tGymUuids = [];
  if (!that.classListParam.isShadowOver) that.classListParam.isShadowOver = 0;

  that.listParams = that.classListParam;
  that.pageListInit();
}
function getChallengeList(){
  const that = this;
  // 初始化
  // that.listParams = that.challengeListParam;
  // that.reqUrl = that.challengeUrl;
  // that.pageListInit();
  app.middleware.requestAjax({
    serAddr: that.challengeUrl,
    data: that.challengeListParam,
    cancelToast: true,
    success: function (res) {
      let temp = res.data || [];
      that.setData({
        matchList: temp
      });
    },
    fail: function (res) {
      that.setData({
        msg: res && res.msg || "请求失败"
      })
    }
  })
}

function changeTime(event){
  const that=this;
  const index = event.currentTarget.dataset.index;
  const idx = event.currentTarget.dataset.idx;
  let times = that.data.times;

  times[index].list[idx].screenStatus = !times[index].list[idx].screenStatus;

  that.setData({
    times,
  })
}
function changeCity(e){
  var index = e.target.dataset.index;
  this.classListParam.cities = [this.data.areas[index].city];

  var dataList = this.data.areas[index].list;
  var storeList = dataList[0].list;
  storeList = clearStore(storeList);
  storeList[0].screenStatus=true;
  this.setData({
    cityIndex:index,
    areaIndex: 0,
    areaList: dataList,
    storeList: storeList
  });
}
function changeAreas(e) {
  var index = e.target.dataset.index;
  var dataList = this.data.areaList[index].list;
  
  this.classListParam.areas = [this.data.areaList[index].area];

  dataList=clearStore(dataList);
  dataList[0].screenStatus = true;
  this.setData({
    areaIndex: index,
    storeIndex: 0,
    storeList: dataList
  })
}
function changeStore(e) {
  const that = this;
  const index = e.target.dataset.index;
  let storeList = that.data.storeList;
  storeList[index].screenStatus = !storeList[index].screenStatus;
  that.setData({
    storeList,
  })
}
function clearStore(list){
  list.forEach(function (val, index) {
    val.screenStatus = false;
  });
  return list;
}
function changeTag(event){
  const that = this;
  const index = event.currentTarget.dataset.index;
  const idx = event.currentTarget.dataset.idx;
  let tags = that.data.tags;

  tags[index].list[idx].screenStatus = !tags[index].list[idx].screenStatus;
  that.setData({
    tags,
  })
}
function changeOver() {
  const that = this;
  that.setData({
    isShadowOver: !that.data.isShadowOver
  })
}
function traverse(status){
  const that=this;
  var tGoodsLabelName = [];
  var intervalTimes=[];
  var tGymUuids=[];
  var tags=that.data.tags;
  tags.forEach(function(val,index){
    var list=val.list;
    list.forEach(function(value,key){
      if (status){
        if (value.screenStatus){
          tGoodsLabelName.push(value.uuid);
        }
      }else{
        value.screenStatus=false;
      }
    })
  });
  var times = that.data.times;
  times.forEach(function (val, index) {
    var list = val.list;
    list.forEach(function (value, key) {
      if (status) {
        if (value.screenStatus) {
          var obj={};
          obj.startTime = value.startTime;
          obj.endTime = value.endTime ;
          intervalTimes.push(obj);
        }
      } else {
        value.screenStatus = false;
      }
    })
  })
  var gyms = that.data.storeList;
  gyms.forEach(function (val, index) {
    if (status) {
      if (val.screenStatus) {
        tGymUuids.push(val.uuid);
      }
    } else {
      val.screenStatus = false;
    }
  })
  gyms[0].screenStatus = true;
  that.setData({
    tags:tags,
    times:times,
    storeList:gyms
  })
  if(status){
    return { tGoodsLabelName, intervalTimes, tGymUuids }
  }
}

function submitScreen(){
  const that=this;
  var param=that.traverse(true);
  that.classListParam.areas = that.classListParam.areas.length > 0 ? that.classListParam.areas : null;

  that.classListParam.tGoodsLabelName = param.tGoodsLabelName.length > 0 ? param.tGoodsLabelName:null;
  that.classListParam.intervalTimes = param.intervalTimes.length > 0 ? param.intervalTimes : null;
  that.classListParam.tGymUuids = param.tGymUuids.length > 0 ? param.tGymUuids : null;
  that.classListParam.isShadowOver = that.data.isShadowOver?1:0;

  that.getClassList();
  that.hideModal();
}
function resetScreen(){
  var areaList = this.data.areas[0].list;
  if(areaList){
    var storeList = areaList[0].list;
  }
  this.setData({
    cityIndex: 0,
    areaIndex: 0,
    areaList: areaList,
    storeList: storeList,
  })
  this.traverse(false);
}

function openLocation(event) {
  const that = this;
  const latitude = event.currentTarget.dataset.latitude;
  const longitude = event.currentTarget.dataset.longitude;
  app.middleware.openLocation({
    latitude,
    longitude,
  });
}

function callBack(res, lists) {
  const that = this;
  var page = that.listParams.page;
  var row = that.listParams.row;
  var isReach = that.listParams.isReach;
  var footMsg = "";
  var tempLists = res.data || [];
  // 当前请求的课程条数
  let length = 0;

  for (let i = 0; i < tempLists.length; i++) {
    length += tempLists[i].lectureEntities.length;
    // 当前健身房是否已经存在
    let isGym = false;
    for (let j = 0; j < lists.length; j++) {
      if (tempLists[i].uuid == lists[j].uuid) {
        isGym = true;
        let lectureEntities = lists[j].lectureEntities || [];
        lists[j].lectureEntities = lectureEntities.concat(tempLists[i].lectureEntities);
      }
    }
    // 当前健身房不存在。则新增一个健身房数据
    if (!isGym) {
      lists.push(tempLists[i]);
    }
  }

  if (row <= length) {
    isReach = false;
    footMsg = "上拉加载更多";
  } else {
    isReach = true;
    footMsg = "没有更多数据啦！";
  }
  that.setData({
    msg: "",
    lists,
    footMsg: footMsg,
  })
  that.listParams.page = page;
  that.listParams.isReach = isReach;
}

// 点击切换筛选标签
function checkDrop(event) {
  const that = this;
  var id;
  if (event) {
    id = event.target.dataset.id;
  } else {
    id = 4;
  }
  that.setData({
    tabId: id
  })
}
// 获取筛选标签
function getSearchLabelByType(type) {
  const that = this;
  // const tabId = that.data.tabId;
  that.typeParams.type = type;
  const cities = that.data.cities || [];
  const regions = that.data.regions || [];
  const gymUuids = that.data.gymUuids || [];
  const labels = that.data.labels || [];
  const intervalTimes = that.data.intervalTimes || [];
  const genres = that.data.genres || [];

  app.middleware.requestAjax({
    serAddr: app.serAddrs.getSearchLabelByType,
    data: that.typeParams,
    cancelToast: true,
    success: function (res) {
      let screens = res.data;
      let temp = {},
        cityIdx = 0,
        areasIdx = 0;

      if (type == 5) {
        temp.areas = screens;
        if(screens[0]){
          var areaList = screens[0].list;
          temp.areaList = areaList;
          if (areaList[0]) {
            var storeList = areaList[0].list;
            storeList[0].screenStatus=true;
            temp.storeList = storeList;
          }
        }
      } else if (type == 4) {
        for (let i = 0; i < screens.length; i++) {
          for (let j = 0; j < screens[i].list.length; j++) {
            labels.forEach((item, index) => {
              if (item == screens[i].list[j].uuid) {
                screens[i].list[j].screenStatus = true;
              }
            })
          }
        }
        temp.tags = screens;
      } else if (type == 3) {
        screens = [screens];
        for (let i = 0; i < screens.length; i++) {
          for (let j = 0; j < screens[i].list.length; j++) {
            intervalTimes.forEach((item, index) => {
              if (item.id == screens[i].list[j].id) {
                screens[i].list[j].screenStatus = true;
              }
            })
          }
        }
        temp.times = screens;
      } else if (type == 2) {
        screens = [{
          name: "门店类型",
          list: screens
        }];
        for (let i = 0; i < screens.length; i++) {
          for (let j = 0; j < screens[i].list.length; j++) {
            genres.forEach((item, index) => {
              if (item == screens[i].list[j].id) {
                screens[i].list[j].screenStatus = true;
              }
            })
          }
        }
        temp.types = screens;
      }
      that.setData(temp);
      if (type == 4) {
        that.getMore(5);
      }else if(type==5){
        that.getMore(3);
      }
    },
    fail: function (res) {

    }
  })
}
function getMore(type) {
  var that = this;
  that.getSearchLabelByType(type);
}
function showModal() {
  // 显示遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
    showModalStatus: true
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
  }.bind(this), 200)
  
}
function hideModal() {
  this.traverse(false);
  // 隐藏遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: false
    })
  }.bind(this), 200)
}